import axios, { InternalAxiosRequestConfig } from "axios";
import router from "@/router/index";
import { getToken, removeToken, csrfToken } from "@/utils/auth";
import code from "@/services/code/index";

function paramsHandle(params: any) {
  const obj: any = {};
  if (params) {
    Object.keys(params).forEach((key) => {
      if (typeof params[key] === "object" && params[key] !== null) {
        obj[key] = JSON.stringify(params[key]);
      } else {
        obj[key] = params[key];
      }
    });
  }

  return {
    ...obj,
    _: new Date().getTime(),
  };
}

// create an axios instance
const service = axios.create({
  withCredentials: true,
  baseURL: `${import.meta.env.VITE_API_URL}`, // api 的 base_url
  timeout: 15000, // 请求超时时间
});

// request interceptor（请求拦截器）
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 让每个请求携带token-- ['authorization']为固定key
    if (getToken()) {
      config.headers["authorization"] = `Bearer ${getToken()}`;
    }
    // 让每个请求携带csrfToken-- ['x-csrf-token']为固定key
    if (csrfToken()) {
      config.headers["x-csrf-token"] = csrfToken();
    }
    console.log(config);

    config.params = paramsHandle(config.params);

    return config;
  },
  (error: any) => {
    // Do something with request error
    Promise.reject(error);
  }
);

// response interceptor（响应拦截器）
service.interceptors.response.use(
  (
    // response => response,
    /**
     * 下面的注释为通过在response里，自定义code来标示请求状态
     * 当code返回如下情况则说明权限有问题，登出并返回到登录页
     * 如想通过 xmlhttprequest 来状态码标识 逻辑可写在下面error中
     * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
     */
    response: { data: any }
  ) => {
    const res = response.data;
    if (res.code == code.code.success) {
      return res;
    } else {
      ElMessage({
        message: `${res.code}:${res.msg}`,
        type: "warning",
        grouping: true,
      });
      switch (Number(res.code)) {
        case 401: //用户登陆超时
          // 清空token
          if (getToken()) {
            removeToken();
          }
          router.push({
            name: "Login",
          });
          break;
        case 403: //用户无权限操作x
          router.push({
            name: "error403",
          });
          break;
        default:
          return Promise.reject(res);
      }
    }
  },
  (error: any) => {
    ElMessage({
      message: `服务器响应失败`,
      type: "error",
      grouping: true,
    });
    return Promise.reject(error);
  }
);

export default service;
